package server.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import server.db.DBUtil;
import server.model.Sex;
import server.model.User;

/**
 * 处理用户数据库操作
 * @author skywalker
 *
 */
public class UserDao {
	
	private static final Logger logger = LogManager.getLogger("server.dao.UserDao");

	public static UserDao getInstance() {
		return UserDaoHolder.instance;
	}
	
	private UserDao() {}
	
	private static class UserDaoHolder {
		private static UserDao instance = new UserDao();
	}
	
	/**
	 * 用户登录，成功返回User对象，否则返回null
	 */
	public User login(String name, String password) {
		if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
			throw new IllegalArgumentException("The name and password cant't be empty or blank");
		}
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			connection = DBUtil.getConnection();
			String sql = "select * from user where name = ? and password = ?";
			ps = connection.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, password);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				User user = new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setPassword(password);
				user.setSignature(rs.getString("signature"));
				user.setSex(Sex.valueOf(rs.getString("sex")));
				user.setBirthday(rs.getTimestamp("birthday"));
				logger.info(name + " 成功登录");
				return user;
			}
		} catch (SQLException e) {
			logger.error(e.getMessage());
		} finally {
			DBUtil.close(connection);
		}
		logger.info(name + " 登录失败");
		return null;
	} 
	
	/**
	 * 添加用户
	 * 此时的用户密码应该是已经经过加密的
	 */
	public void save(User user) {
		Connection connection = null;
		PreparedStatement ps = null;
		try {
			connection = DBUtil.getConnection();
			String sql = "insert into user values(null, ?, ?, ?, ?, ?, ?)";
			ps = connection.prepareStatement(sql);
			ps.setString(1, user.getName());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getSex().name());
			ps.setTimestamp(4, new Timestamp(user.getBirthday().getTime()));
			ps.setString(5, user.getAvatar());
			ps.setString(6, user.getSignature());
			ps.execute();
			logger.info(user.getName() + " 保存成功");
		} catch (SQLException e) {
			logger.info(user.getName() + " 保存失败");
			logger.error(e.getMessage());
		} finally {
			DBUtil.close(connection, ps);
		}
	}
	
}
